// pages/mine/mine.js
const re = require("../../utils/request.js")
Page({
  /**
   * 页面的初始数据
   */
  data: {
    info: {
      "id": "",
      "name": "",
      "avatarUrl": "",
      "avatar": "",
      "email": "",
      "classId": 1,
      "className": "",
      "semester": 1,
      "token": ""
    }
  },
  toScan() {
    wx.scanCode({
      success(res) {
        const code = res.result
        const activityId = code.split('@')?.[1] ?? ""
        const studentId = JSON.parse(wx.getStorageSync('userInfo'))["id"]
        if (activityId) {
          // 提交活动
          const data = {
            activityId: activityId,
            studentId: studentId,
            code: code
          }
          console.log(data)
          re.postRequest('/score-record/method1-2', data).then(res => {
            if (res.msg) {
              wx.showToast({
                title: res.msg,
                icon: 'success',
                duration: 4000
              })
            }
          })
        }
      }
    })
  },
  toCode() {
    const urls = []
    const stuId = JSON.parse(wx.getStorageSync('userInfo'))['id']
    urls.push(`${re.serverUrl}/code/student/${stuId}`)
    wx.previewImage({
      urls: urls
    })
  },
  logout() {
    wx.showModal({
      title: '提示',
      content: '确认是否退出',
      success (res) {
        if (res.confirm) {
          wx.clearStorageSync()
          wx.redirectTo({
            url: '/pages/index/index',
          })
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 获取 userInfo
    // 解析 userInfo 到 json 并获取 id
    const userInfo = wx.getStorageSync('userInfo')
    if (userInfo) {
      const id = JSON.parse(userInfo)['id']

      re.getRequest(`/student/info/${id}`).then(res => {
        const data = res.data
        if (res.data) {
          data['avatarUrl'] = re.serverUrl + '/img/' + data.avatar
          this.setData({
            info: data,
          })
        }
      })
    }
    // 调用 /student/info/{id}
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})